﻿using System.Collections.Generic;

namespace Nutilities.Collections.Monitors
{
    public class ListMonitor<T>
    {
        public object SyncRoot { get; private set; }
        public List<T> List { get; private set; }

        public int Count
        {
            get
            {
                return List.Count;
            }
        }

        public ListMonitor(List<T> list)
        {
            List = list;
            SyncRoot = new object();
        }

        // Altering operations
        public void Add(T item)
        {
            lock (SyncRoot)
            {
                List = new List<T>(List);
                List.Add(item);
            }
        }

        public bool Remove(T item)
        {
            lock (SyncRoot)
            {
                List = new List<T>(List);
                return List.Remove(item);
            }
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            lock (SyncRoot)
            {
                List.CopyTo(array, arrayIndex);
            }
        }

        public int IndexOf(T item)
        {
            lock (SyncRoot)
            {
                return List.IndexOf(item);
            }
        }

        public void Insert(int index, T item)
        {
            lock (SyncRoot)
            {
                List = new List<T>(List);
                List.Insert(index, item);
            }
        }

        public void RemoveAt(int index)
        {
            lock (SyncRoot)
            {
                List = new List<T>(List);
                List.RemoveAt(index);
            }
        }

        public void Clear()
        {
            lock (SyncRoot)
            {
                List = new List<T>();
            }
        }

        public bool Contains(T item)
        {
            lock (SyncRoot)
            {
                return List.Contains(item);
            }
        }

        public T this[int index]
        {
            get
            {
                // Non-altering operation
                lock (SyncRoot)
                {
                    return List[index];
                }
            }
            set
            {
                // Altering operation
                lock (SyncRoot)
                {
                    List = new List<T>(List);
                    List[index] = value;
                }
            }
        }
    }
}
